<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    :title="title"
    width="600"
    draggable
    @close="close"
    :z-index="2000"
  >
    <template #default>
      <el-form ref="ruleFormRef" label-width="180px">
        <el-form-item label="选择所要复制的SKU" required>
          <el-select class="w-full" v-model="copySKU" clearable>
            <el-option
              v-for="(item, index) in form.goods_sku"
              :key="index"
              :label="item.custom_sku"
              :value="item.custom_sku"
              >{{ item.custom_sku }}
              <span v-if="item.sku">({{ item.sku }})</span></el-option
            >
          </el-select>
          <el-checkbox
            v-model="allSKU"
            label="所有SKU都复制"
            :true-label="1"
            :false-label="0"
            size="large"
          />
        </el-form-item>
        <div class="text-[#999]">
          注:此操作用于快速复制所选SKU的信息到当前SKU分页中;若勾选所有SKU都复制，则所选SKU信息复制到其他所有SKU信息中，不仅是当前分页SKU。
        </div>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="confirmCopy">确认</el-button>
    </template>
  </el-dialog>
</template>
<script setup name="AuditModal">
import { reactive, toRefs, getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
const { proxy } = getCurrentInstance();
import { deepClone } from "@/utils/index";
const emits = defineEmits(["query"]);
let form = reactive(inject("form"));

const copyTypeMap = new Map([
  ["all", "复制SKU信息"],
  ["picture", "复制产品图片"],
  ["remark", "复制备注信息"],
  ["supplier", "复制供应商信息"],
  ["weightSizeInfo", "复制重量尺寸信息"],
]);

const data = reactive({
  visible: false,
  item: null,
  active: null,
  copySKU: null,
  copyType: null,
  title: null,
  allSKU: false,
  load: false,
});

const { visible, active, copySKU, copyType, title, allSKU, load } = toRefs(data);

const open = async (type, data) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  copyType.value = type;
  title.value = copyTypeMap.get(type);
  active.value = data;
  visible.value = true;
};

const confirmCopy = () => {
  if (!copySKU.value) {
    ElMessage.error("请选择需要复制的SKU");
    return;
  }
  if (!allSKU.value && copySKU.value == active.value) {
    ElMessage.error("不能复制当前SKU, 请检查重试");
    return;
  }

  const goods_sku = deepClone(form.value.goods_sku);
  const activeIndex = form.value.goods_sku.findIndex(
    (item) => item.custom_sku == active.value || item.sku == active.value
  );
  const copyIndex = form.value.goods_sku.findIndex(
    (item) => item.custom_sku == copySKU.value || item.sku == copySKU.value
  );

  if (copyType.value == "all") {
    if (allSKU.value) {
      copyToOtherObjects(copyIndex, form.value.goods_sku);
      form.value.goods_sku.forEach((item, index) => {
        if (index != copyIndex) {
          const sourceSuppliers = goods_sku[copyIndex].goods_sku_supplier;

          const sourceAccessories = goods_sku[copyIndex]?.goods_sku_accessories || [];
          if (item.goods_sku_accessories.length) {
            item.goods_sku_accessories = item.goods_sku_accessories.map((i) => ({
              ...i,
              delete: 1,
            }));
          }

          const newAccessories = sourceAccessories.map((i) => ({
            ...i,
            id: "",
          }));
          item.goods_sku_accessories.push(...newAccessories);

          item.goods_sku_relation = [];

          mergeSuppliers(sourceSuppliers, item.goods_sku_supplier);
          console.log("mergeSuppliers");
          console.log(item.goods_sku_supplier);
        }
      });
    } else {
      const copyData = deepCopyWithPreserveId(
        goods_sku[copyIndex],
        goods_sku[activeIndex],
        goods_sku[activeIndex].custom_sku
      );
      form.value.goods_sku[activeIndex] = copyData;

      const sourceAccessories =
        form.value.goods_sku[copyIndex].goods_sku_accessories || [];
      if (form.value.goods_sku[activeIndex].goods_sku_accessories.length) {
        form.value.goods_sku[activeIndex].goods_sku_accessories = form.value.goods_sku[
          activeIndex
        ].goods_sku_accessories.map((i) => ({
          ...i,
          delete: 1,
        }));
      }

      const newAccessories = sourceAccessories.map((i) => ({
        ...i,
        id: "",
      }));
      form.value.goods_sku[activeIndex].goods_sku_accessories.push(...newAccessories);

      console.log("form.value.goods_sku[activeIndex].goods_sku_accessories");
      console.log(form.value.goods_sku[activeIndex].goods_sku_accessories);
      console.log("newAccessories");
      console.log(newAccessories);

      // 合并供应商
      // 复制供应商
      form.value.goods_sku[activeIndex].goods_sku_relation = [];

      const sourceSuppliers = goods_sku[copyIndex].goods_sku_supplier;
      // 目标当前供应商
      // const targetSuppliers = form.value.goods_sku[activeIndex].goods_sku_supplier.filter(
      //   (supplier) => supplier.delete !== 1
      // );
      mergeSuppliers(
        sourceSuppliers,
        form.value.goods_sku[activeIndex].goods_sku_supplier
      );
    }
  } else if (copyType.value == "picture") {
    if (allSKU.value) {
      form.value.goods_sku.forEach((item, index) => {
        if (index != copyIndex) {
          const copyData = deepCopyWithPreserveId(
            goods_sku[copyIndex].goods_sku_gallery,
            item.goods_sku_gallery
          );
          item.goods_sku_gallery = copyData;
        }
      });
    } else {
      const copyData = deepCopyWithPreserveId(
        goods_sku[copyIndex].goods_sku_gallery,
        goods_sku[activeIndex].goods_sku_gallery
      );
      form.value.goods_sku[activeIndex].goods_sku_gallery = copyData;
    }
  } else if (copyType.value == "remark") {
    if (allSKU.value) {
      form.value.goods_sku.forEach((item, index) => {
        if (index != copyIndex) {
          item.goods_sku_remark = removeIds(goods_sku[copyIndex].goods_sku_remark);
        }
      });
    } else {
      form.value.goods_sku[activeIndex].goods_sku_remark = removeIds(
        goods_sku[copyIndex].goods_sku_remark
      );
    }
  } else if (copyType.value == "supplier") {
    if (allSKU.value) {
      form.value.goods_sku.forEach((item, index) => {
        if (index != copyIndex) {
          const sourceSuppliers = goods_sku[copyIndex].goods_sku_supplier;
          const targetSuppliers = item.goods_sku_supplier.filter(
            (supplier) => supplier.delete !== 1
          );
          mergeSuppliers(sourceSuppliers, item.goods_sku_supplier);
        }
      });
    } else {
      const sourceSuppliers = goods_sku[copyIndex].goods_sku_supplier;
      const targetSuppliers = form.value.goods_sku[activeIndex].goods_sku_supplier.filter(
        (supplier) => supplier.delete !== 1
      );
      mergeSuppliers(
        sourceSuppliers,
        form.value.goods_sku[activeIndex].goods_sku_supplier
      );
      console.log("mergeSuppliers");
      console.log(form.value.goods_sku[activeIndex].goods_sku_supplier);
    }
  } else if (copyType.value == "weightSizeInfo") {
    const sourceItem = form.value.goods_sku[copyIndex];
    // 缓存属性值
    const {
      gross_weight_g,
      net_weight_g,
      packing_weight_g,
      packing_size_cm,
      product_size_cm,
      packing_qty_size_cm,
      packing_gross_weight_kg,
      cabinets_qty,
      packing_qty,
    } = sourceItem;
    if (allSKU.value) {
      form.value.goods_sku.forEach((item, index) => {
        if (index != copyIndex) {
          updateItem(item, {
            gross_weight_g,
            net_weight_g,
            packing_weight_g,
            packing_size_cm,
            product_size_cm,
            packing_qty_size_cm,
            packing_gross_weight_kg,
            cabinets_qty,
            packing_qty,
          });
        }
      });
    } else {
      updateItem(form.value.goods_sku[activeIndex], {
        gross_weight_g,
        net_weight_g,
        packing_weight_g,
        packing_size_cm,
        product_size_cm,
        packing_qty_size_cm,
        packing_gross_weight_kg,
        cabinets_qty,
        packing_qty,
      });
    }
  }
  close();
};

// 更新单个元素的函数
const updateItem = (item, properties) => {
  item.gross_weight_g = properties.gross_weight_g;
  item.net_weight_g = properties.net_weight_g;
  item.packing_weight_g = properties.packing_weight_g;
  item.packing_size_cm = properties.packing_size_cm;
  item.product_size_cm = properties.product_size_cm;
  item.packing_qty_size_cm = properties.packing_qty_size_cm;
  item.packing_gross_weight_kg = properties.packing_gross_weight_kg;
  item.cabinets_qty = properties.cabinets_qty;
  item.packing_qty = properties.packing_qty;
};

const keysToPreserve = [
  "id",
  "sku_id",
  "sku",
  "custom_sku",
  "sku_cn_title",
  "sku_en_title",
  "goods_sku_title",
  "sku_code",
  "main_attribute",
  "specifications",
  "sku_specification",
  "title",
  "color",
  "size",
  "attributes",
  "dev_add_time",
  "dev_review_time",
  "logistics_review_time",
  "sai_he_sku",
  "dev_status",
  "supply_status",
  "supply_status_text",
  "product_status",
  "product_status_text",
  "sales_status",
  "sales_status_text",
  "goods_sku_supplier",
  "latest_purchase_price",
  "lowest_purchase_price",
  "average_purchase_price",
  "create_user",
  "create_user_text",
  "goods_sku_accessories",
  "goods_sku_relation_old",
];

const deepCopyWithPreserveId = (source, target, custom_sku) => {
  for (const key in source) {
    if (source.hasOwnProperty(key)) {
      if (keysToPreserve.includes(key)) {
        continue;
      } else if (Array.isArray(source[key])) {
        target[key] = source[key].map((item, index) => {
          if (typeof item === "object" && item !== null) {
            return deepCopyWithPreserveId(item, target[key]?.[index] || {});
          } else {
            return item;
          }
        });
      } else if (typeof source[key] === "object" && source[key] !== null) {
        target[key] = deepCopyWithPreserveId(source[key], target[key] || {});
      } else {
        target[key] = source[key];
        if (custom_sku) {
          target["custom_sku"] = custom_sku;
        }
      }
    }
  }
  return target;
};

const removeIds = (obj) => {
  const item = obj;
  delete item.id;
  delete item.sku_id;
  delete item.spu_id;
  return item;
};
const removeArrayIds = (list, sku) => {
  list &&
    list.forEach((item) => {
      if (item.sku) {
        item.sku = sku;
      }
      if (item.goods_sku_customs) {
        delete item.goods_sku_customs.id;
      }
      delete item.id;
      delete item.sku_id;
      delete item.spu_id;
    });
  return list;
};

const copyToOtherObjects = (sourceIndex, array) => {
  const sourceObject = array[sourceIndex];
  for (let i = 0; i < array.length; i++) {
    if (i !== sourceIndex) {
      const copiedData = deepCopyWithPreserveId(
        sourceObject,
        array[i],
        array[i].custom_sku
      );
      array[i] = copiedData;
    }
  }
};
// 合并供应商
const mergeSuppliers = (sourceSuppliers, targetSuppliers) => {
  if (targetSuppliers.length) {
    sourceSuppliers.forEach((sourceItem, sourceIndex) => {
      let found = false;
      targetSuppliers.forEach((targetItem, targetIndex) => {
        if (targetItem.supplier_id === sourceItem.supplier_id && !targetItem.delete) {
          // 如果 country_id 和 platform_id 相同，则复制内容
          const isDefaultSupplier = targetItem.is_default_supplier;
          const id = targetItem.id;
          const spu_id = targetItem.spu_id;
          const sku_id = targetItem.sku_id;
          const customs_id = targetItem.goods_sku_customs?.id;
          const trade_agent_id = targetItem.goods_sku_trade_agent?.id;
          let source_goods_sku_customs_info = null;
          if (sourceItem.goods_sku_customs) {
            source_goods_sku_customs_info = mergeGoodsSKUCustomsInfo(
              targetItem.goods_sku_customs.goods_sku_customs_info, // 深拷贝
              sourceItem.goods_sku_customs.goods_sku_customs_info
            );
            sourceItem.goods_sku_customs.id = customs_id;
            sourceItem.goods_sku_customs.goods_sku_customs_info = source_goods_sku_customs_info;
          } else {
            sourceItem.goods_sku_customs = {};
          }

          sourceItem.goods_sku_identification_processing = mergeidentificationprocessing(
            targetItem.goods_sku_identification_processing,
            sourceItem.goods_sku_identification_processing
          );
          if (sourceItem.goods_sku_trade_agent) {
            sourceItem.goods_sku_trade_agent.id = trade_agent_id;
          }

          Object.assign(targetItem, deepClone(sourceItem));

          console.log("targetItem");
          console.log(targetItem.goods_sku_trade_agent);

          targetItem.is_default_supplier = isDefaultSupplier;
          targetItem.id = id;
          targetItem.spu_id = spu_id;
          targetItem.sku_id = sku_id;
          found = true;
        }
      });
      if (!found) {
        sourceItem.is_default_supplier = 0;
        sourceItem.id = "";
        sourceItem.spu_id = "";
        sourceItem.sku_id = "";
        if (sourceItem.goods_sku_customs) {
          const targetSuppliers = sourceItem.goods_sku_customs.goods_sku_customs_info.filter(
            (supplier) => supplier.delete !== 1
          );
          if (targetSuppliers.length) {
            sourceItem.goods_sku_customs.goods_sku_customs_info = removeArrayIds(
              sourceItem.goods_sku_customs.goods_sku_customs_info
            );
          }
        } else {
          sourceItem.goods_sku_customs = {};
        }
        sourceItem.goods_sku_identification_processing = removeArrayIds(
          sourceItem.goods_sku_identification_processing
        );
        sourceItem.goods_sku_trade_agent.id = "";
        sourceItem.goods_sku_customs.id = "";
        targetSuppliers.push(sourceItem);
      }
    });
  } else {
    const newsourceSuppliers = sourceSuppliers.map((i) => ({
      ...i,
      id: "",
      sku_id: "",
      goods_sku_customs: {
        ...i.goods_sku_customs,
        id: "",
        goods_sku_customs_info: removeArrayIds(
          i.goods_sku_customs.goods_sku_customs_info
        ),
      },
      goods_sku_trade_agent: {
        ...i.goods_sku_trade_agent,
        id: "",
      },
      goods_sku_identification_processing: removeArrayIds(
        i.goods_sku_identification_processing
      ),
    }));

    targetSuppliers.push(...newsourceSuppliers);
  }
};

// 合并清关信息
const mergeGoodsSKUCustomsInfo = (target, source) => {
  const sourceFilter = source
    .filter((supplier) => supplier.delete !== 1)
    .map((item) => ({ ...item }));
  if (sourceFilter.length) {
    sourceFilter.forEach((sourceItem) => {
      let found = false;
      target.forEach((targetItem) => {
        if (
          targetItem.country_id === sourceItem.country_id &&
          targetItem.platform_id === sourceItem.platform_id
        ) {
          // 如果 country_id 和 platform_id 相同，则复制内容
          delete sourceItem.id;
          delete sourceItem.sku_id;
          delete sourceItem.goods_sku_custom_id;
          Object.assign(targetItem, sourceItem);
          found = true;
        }
      });
      if (!found) {
        // 如果没有找到匹配项，则将 target 的元素推入 source
        delete sourceItem.id;
        delete sourceItem.sku_id;
        delete sourceItem.goods_sku_custom_id;
        target.push(sourceItem);
      }
    });

    return target;
  } else {
    return removeArrayIds(target);
  }
};

const mergeidentificationprocessing = (target, source) => {
  if (target.length) {
    const sourceFilter = target
      .filter((item) => item.delete !== 1)
      .map((item) => {
        if (item.id) {
          return {
            ...item,
            delete: 1,
          };
        } else {
          return item;
        }
      });
    sourceFilter.push(...removeArrayIds(source));
    return sourceFilter;
  } else {
    return removeArrayIds(source);
  }
};
const close = () => {
  proxy.resetForm("formRef");
  visible.value = false;
};

defineExpose({ open });
</script>
